import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import '../Robot.dart';
import '../details.dart';
import '../pojo.dart';

const platformMethodChannel = MethodChannel(
  'com.abc.robot01.flutter.huxingxuanze',
);

///户型选择
class HuXingProvider extends ChangeNotifier {
  //客户手机
  final TextEditingController textEditingController = TextEditingController();

  void setTextFieldValue(String value) {
    textEditingController.text = value;
    notifyListeners();
  }

  void reset() {
    selectedIndex = -1;
    enable1 = false;
    enable2 = false;
    _selectedHouseType = "全部";
    _selectedDesigner = "全部";
    _name = '';
    notifyListeners();
  }

  ///界面当前输入的内容:
  //户型类型名称
  List<String> names = [];

  ///户型开始
  String _selectedHouseType = "全部";

  String get selectedHouseType => _selectedHouseType;

  void setSelectedHouseType(String type) {
    _selectedHouseType = type;
    notifyListeners();
  }

  bool _show = false;

  bool get show => _show;

  void setShow(bool show) {
    _show = show;
    notifyListeners();
  }

  String _selectedDesigner = "全部";

  String get selectedDesigner => _selectedDesigner;

  void setSelectedDesigner(String type) {
    _selectedDesigner = type;
    notifyListeners();
  }

  ///户型结束

  ///户型名称开始
  // Customer information fields
  String _name = "";

  // Getter methods for each property
  String get name => _name;

  void setName(String name) {
    _name = name;
    notifyListeners();
  }

  ///户型名称结束

  int selectedIndex = -1;

  void setIndex(int index) {
    selectedIndex = index;
    if (selectedIndex >= 0) {
      if (_list[selectedIndex].renderCount > 0) {
        enable1 = true;
      } else {
        enable1 = false;
      }
      enable2 = true;
    }
    notifyListeners();
  }

  bool clicked= false;

  void  a1(){
    clicked=false;
  }

  ///户型数据
  void onClick1() async {
    if(enable1){
      if(clicked == false) {
        clicked = true;
        final bool result = await platformMethodChannel.invokeMethod(
          'start_HuXingShuJuActivity',
          {'housePlansId': _list[selectedIndex].id},
        );
      }
    }
  }
  void onClick2() async {
    if(enable2){
      if(clicked == false) {
        clicked = true;
        _isLoading = true;
        notifyListeners();
      final dynamic result = await platformMethodChannel.invokeMethod(
        'start_HuXingTiaoZheng',
        {
          'housePlansId': _list[selectedIndex].id,
          'thumbnail': _list[selectedIndex].pictureUrl,
        },
      );
      _isLoading =false;
        notifyListeners();
    }
    }
  }

  ///查询结果
  List<HouseLayoutItem> _list = [];

  List<HouseLayoutItem> get houseLayoutList => _list;

  List<UserInfo> _designers = [];

  List<UserInfo> get designers => _designers;

  bool _isLoading = false;

  ///底部的2个button
  bool enable1 = false;

  bool enable2 = false;

  void setEnable2(bool v) {
    enable2 = v;
    notifyListeners();
  }

  void setEnable1(bool v) {
    enable1 = v;
    notifyListeners();
  }

  //用户当前输入的号码
  String _phoneNumber = "";

  String get phoneNumber => _phoneNumber;

  void setPhoneNumber(String text) {
    _phoneNumber = text;
    filteredList =
        customersList.where((item) => item.startsWith(text)).toList();
    // 输出新列表
    print(filteredList); // 输出: [123John, 123Alice, 123Chris]
    notifyListeners();
  }

  bool get isLoading => _isLoading;

  //户型类型
  List<SysDictType> data = [];

  late List<String> customersList;

  //输入的号码过滤之后的结果
  late List<String> filteredList;

  ///获取户型类型类别
  Future<void> getSysDicByType({
    required String accessToken,
    required String type,
  }) async {
    print("getSysDicByType start");

    var url = Uri.https(host, 'dict/getSysDicByType/$type');
    final uri = url.replace(
      queryParameters: {"access_token": accessToken, "type": type},
    );

    // print("toJson: ${a}");
    final response = await http.get(
      uri,
      headers: {"Content-Type": "application/json; charset=UTF-8"},
    );

    if (response.statusCode == 200) {
      print("系统字典 response：${response.body}");
      Map<String, dynamic> jsonResponse2 = json.decode(response.body);
      HouseTypeResponse response2 = HouseTypeResponse.fromJson(jsonResponse2);
      data = response2.data;
      // Access parsed data
      for (var houseType in data) {
        print('Name: ${houseType.name}, Code: ${houseType.code}');
      }
      names = data.map((item) => item.name).toList();
      notifyListeners();
      return;
    } else {
      throw Exception('Failed to fetch products: ${response.reasonPhrase}');
    }
  }

  Future<void> getDesigners({
    required String accessToken,
    required String userId,
    required String companyId,
  }) async {
    print("getDesigners start");
    Condition8 condition = Condition8(name: '');
    FetchDataRequest9<Condition8> request = FetchDataRequest9<Condition8>(
      condition: condition,
    );
    print("condition: ${condition.toJson()}");
    var url = Uri.https(host, 'housePlans/searchDesigner');
    final uri = url.replace(
      queryParameters: {
        "access_token": accessToken,
        "userId": userId,
        "companyId": companyId,
      },
    );
    final a = jsonEncode(request.toJson((condition) => condition.toJson()));
    print("getDesigners:request: ${a}");
    final response = await http.post(
      uri,
      headers: {"Content-Type": "application/json; charset=UTF-8"},
      body: a,
    );
    if (response.statusCode == 200) {
      print("getDesigners response：${response.body}");
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      _isLoading = false;
      // print("getCompanyProduct end");
      var a = ApiResponse<DataInfo>.fromJson(
        jsonResponse,
        (data) => DataInfo.fromJson(data),
      );
      _designers = a.data!.list;
      for (var item in _designers) {
        print(item.toJson().toString());
      }
      notifyListeners();
      print("getDesigners end");
      return;
    } else {
      throw Exception('Failed to fetch products: ${response.reasonPhrase}');
    }
  }

  Future<void> getHouseLayouts({
    required String accessToken,
    required String userId,
    required String companyId,
  }) async {
    selectedIndex = -1;
    notifyListeners();
    print("getHouseLayouts start");

    // 创建 Condition3 对象
    String a1 = '';
    if (_selectedHouseType == "全部") {
    } else {
      SysDictType firstB = data.firstWhere(
        (item) => item.name == _selectedHouseType,
      );
      a1 = firstB.code;
    }

    String createUserIds =
        _selectedDesigner == "全部"
            ? ''
            : designers
                .firstWhere((item) => item.nickname == _selectedDesigner)
                .id;

    Condition2 condition = Condition2(
      name: name,
      houseType: a1,
      createUserIds: createUserIds,
    );

    FetchDataRequest9<Condition2> request = FetchDataRequest9<Condition2>(
      condition: condition,
    );

    print("condition: ${condition.toJson()}");

    var url = Uri.https(host, 'housePlans/pageWithReadResult');
    final uri = url.replace(
      queryParameters: {
        "access_token": accessToken,
        "userId": userId,
        "companyId": companyId,
      },
    );

    final a = jsonEncode(request.toJson((condition) => condition.toJson()));
    print("request: ${a}");
    final response = await http.post(
      uri,
      headers: {"Content-Type": "application/json; charset=UTF-8"},
      body: a,
    );

    if (response.statusCode == 200) {
      // print("户型数据  response：${response.body}");
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      _isLoading = false;
      // print("getCompanyProduct end");
      var a = ApiResponse<HouseLayoutData>.fromJson(
        jsonResponse,
        (data) => HouseLayoutData.fromJson(data),
      );
      // _list = a.data!.list.sublist(0,30);
      _list = a.data!.list;
      for (var item in _list) {
        // print(item.toJson().toString());
      }
      notifyListeners();
      print("getHouseLayouts end");
      return;
    } else {
      throw Exception('Failed to fetch products: ${response.reasonPhrase}');
    }
  }

  Future<void> searchByPhone({
    required String accessToken,
    required String userId,
    required String companyId,
  }) async {
    print("searchByPhone start");
    _isLoading = true;
    notifyListeners();
   // await Future.delayed(Duration(seconds: 5));
    print("getByPhone:" + textEditingController.text);
    final bool result = await platformMethodChannel.invokeMethod(
      'search_by_phone',
      {'phone': textEditingController.text},
    );
    _isLoading=false;
    notifyListeners();
    print("searchByPhone end");
    return;
  }

  Future<void> getCustomers() async {
    print("getCompanyProduct start");
    // _isLoading = true;
    // notifyListeners();
    final accessToken = Robot.accessToken;
    final userId = Robot.userId;
    final companyId = Robot.companyId;

    // 创建 Condition3 对象
    Condition3 condition = Condition3();

    // 创建 FetchDataRequest9 对象
    FetchDataRequest9<Condition3> request = FetchDataRequest9<Condition3>(
      condition: condition,
    );

    var url = Uri.https(host, 'userOrderCustomer/page');
    final uri = url.replace(
      queryParameters: {
        "access_token": accessToken,
        "userId": userId,
        "companyId": companyId,
      },
    );

    final a = jsonEncode(request.toJson((condition) => condition.toJson()));
    // print("toJson: ${a}");
    final response = await http.post(
      uri,
      headers: {"Content-Type": "application/json; charset=UTF-8"},
      body: a,
    );

    if (response.statusCode == 200) {
      print("response：${response.body}");
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      // _isLoading = false;
      // print("getCompanyProduct end");
      var a = ApiResponse<Data9>.fromJson(
        jsonResponse,
        (data) => Data9.fromJson(data),
      );
      a.data!.list.forEach((item) {
        // print(item.toJson());
      });
      customersList =
          a.data!.list
              .map((item) => item.customerPhone + " " + item.customerName)
              .toList();
      customersList.forEach((item) {
        print(item);
      });

      filteredList = customersList;
      notifyListeners();
      return;
    } else {
      throw Exception('Failed to fetch products: ${response.reasonPhrase}');
    }
  }



}
